package design.event;

import java.util.HashSet;
import java.util.Set;

/**
 * 事件源(被观察者)
 */
public class Writer {
    //作者用户信息
    private User user;
    //作者新书
    private String lastBook;
    //监听器列表
    Set<WriterListener> writerListenerList = new HashSet<>();

    public Writer(String userName) {
        super();
        //初始化用户信息
        user = new User();
        user.setUserName(userName);
        //将作者添加到作者管理器中
        WriterManager.getInstance().addWriter(this);
    }

    //作者发布新书动作
    public void pushBook(String bookName) {
        System.out.println("事件源 : " + user.getUserName() + ";   发布了新书: " + bookName + " ... ... ");
        lastBook = bookName;
        //设置被观察发生改变的状态,并通知所有监听器
        triggerEvent();
    }

    //触发事件通知所有监听器
    private void triggerEvent() {
        WriterEvent writerEvent = new WriterEvent(this);
        for (WriterListener writerListener : writerListenerList) {
            writerListener.addNovel(writerEvent);
        }
    }

    //监听器的添加
    public void addWriterListener(WriterListener writerListener) {
        writerListenerList.add(writerListener);
    }

    //监听器的取消
    public void removeWriterListener(WriterListener writerListener) {
        writerListenerList.remove(writerListener);
    }

    public String getLastBook() {
        return lastBook;
    }

    public void setLastBook(String lastBook) {
        this.lastBook = lastBook;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
